
/**
 * @Title: HttpClientFluentStu.java
 * @Package
 * @Description: TODO
 * @author tbc
 * @date 2016年7月3日 上午5:04:26
 * @version
 */
package tbg.http;

import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.google.gson.Gson;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import tbg.http.Result;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;

/**
 * Created by siyu on 16/7/3. http://amdms.foton.com.cn/
 * http: http://amdms.foton.com.cn
 * user: dmsadmin@foton.com.cn
 * pass: 8312wang
 */
public class HttpClientFluentStu {

    static int n = 1;

    /**
     * addHeader("Host", "amdms.foton.com.cn"); :
     * :queryData.start=0&queryData.limit=10&queryData.vehicleStatus=&queryData.
     * orgaId=&queryData.stockDaysEnd=&queryData.stockDays=&queryData.
     * productGroup=&queryData.dealerId=&queryData.vin=LRDV6PDB6EH001452
     */
    public static void main(String[] args) throws IOException {
        long startTime = System.currentTimeMillis();
        String body = "queryData.start=0&queryData.limit=10&queryData.vehicleStatus=&queryData.orgaId=&queryData.stockDaysEnd=&queryData.stockDays=&queryData.productGroup=&queryData.dealerId=&queryData.vin=";
//		String coockie = "username=dmsadmin@foton.com.cn; style=blue; JSESSIONID=3zKhXNJbjRDLvwjjQyCsMlywl8D5Gy1ryyh1nj3WTsPvdXttlVCB!-431778453";
        String coockie = "JSESSIONID=qxSKYyrCSMFwXnMT8lQXsTb1PkJGB2g1yDGLjm0yrNkh15bGfjqy!1356908041; style=blue";

        File file = new File("c:\\Users\\tbc\\Desktop\\vin.txt");
        List<String> vins = Files.readLines(file, Charset.forName("UTF-8"));

        List<Map<String, Object>> outList = Lists.newArrayList();

        vins.forEach(it -> {
            System.out.println("发送第" + n++ + "次请求, time = " + getNowTime());
            Request request = getInitRequest();
            String resultjson = null;
            try {
                resultjson = request.addHeader("Cookie", coockie)//
                        .bodyString(body + it, ContentType.APPLICATION_FORM_URLENCODED)//
                        .execute()//
                        .returnContent()//
                        .asString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("->请求完成, time = " + getNowTime());
            //
            // System.out.println("content : \n" + resultjson);
            Result result = new Gson().fromJson(resultjson, Result.class);
            List<Map<String, Object>> list = result.getList();
            Map<String, Object> row = list.get(0);
            outList.add(row);
            // 打印看看
            String vin = row.get("vin").toString();
            String productGroupName = row.get("productGroupName").toString();
            String znbbm = row.get("znbbm").toString();

            System.out.println("vin: " + vin);
            System.out.println("产品组: " + productGroupName);
            System.out.println("内部编号: " + znbbm);
        });

        System.out.println("请求全部完成，正在输出到excel文件");
        File outFile = new File("c:\\Users\\tbc\\Desktop\\amdms.xlsx");
        XSSFWorkbook book = new XSSFWorkbook();
        XSSFSheet sheet = book.createSheet("sheet1");

        for (int i = 0; i < outList.size(); i++) {
            Map<String, Object> _row = outList.get(i);
            XSSFRow row = sheet.createRow(i);

            XSSFCell c1 = row.createCell(0);
            c1.setCellValue(_row.get("vin").toString());
            XSSFCell c2 = row.createCell(1);
            c2.setCellValue(_row.get("productGroupName").toString());
            XSSFCell c3 = row.createCell(2);
            c3.setCellValue(_row.get("znbbm").toString());

        }
        OutputStream os = new FileOutputStream(outFile);
        book.write(os);
        os.flush();
        os.close();

        System.out.println("全部工作完成...");
        System.out.println("共耗时： " + (System.currentTimeMillis() - startTime));

    }

    public static Request getInitRequest() {
        return Request.Post("http://amdms.foton.com.cn/vehivle/dealerVehicleQueryList.html")//
                .addHeader("Host", "amdms.foton.com.cn")//
                .addHeader("User-Agent",
                        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0")//
                .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
                .addHeader("addAccept-Encoding", "gzip, deflate").addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .addHeader("Referer",
                        "http://amdms.foton.com.cn/vehivle/goFactoryVehivleQuery.html?time="
                                + System.currentTimeMillis())
                .addHeader("Connection", "keep-alive").addHeader("Pragma", "no-cache")
                .addHeader("Cache-Control", "no-cache").version(HttpVersion.HTTP_1_1);
    }

    public static void test() throws ClientProtocolException, IOException {
        String body = "queryData.start=0&queryData.limit=10&queryData.vehicleStatus=&queryData.orgaId=&queryData.stockDaysEnd=&queryData.stockDays=&queryData.productGroup=&queryData.dealerId=&queryData.vin=LRDS6PEB1GR002796";
        String coockie = "JSESSIONID=NBJyX4fGm1RNyFwK1jfjHkvQH3nycPhPyr8Qy2KyZ42VXMsnlJh6!-1402367776; style=blue; username=dmsadmin@foton.com.cn";

        String r = Request.Post("http://amdms.foton.com.cn/vehivle/dealerVehicleQueryList.html")//
                .addHeader("Host", "amdms.foton.com.cn")//
                .addHeader("User-Agent",
                        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0")//
                .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
                .addHeader("addAccept-Encoding", "gzip, deflate").addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .addHeader("Referer",
                        "http://amdms.foton.com.cn/vehivle/goFactoryVehivleQuery.html?time="
                                + System.currentTimeMillis())
                .addHeader("Cookie", coockie)

                .addHeader("Connection", "keep-alive").addHeader("Pragma", "no-cache")
                .addHeader("Cache-Control", "no-cache").bodyString(body, ContentType.APPLICATION_FORM_URLENCODED)
                .version(HttpVersion.HTTP_1_0).execute().returnContent().asString();

        System.out.println("content : \n" + r);
        Result result = new Gson().fromJson(r, Result.class);
        List<Map<String, Object>> list = result.getList();
        Map<String, Object> row = list.get(0);
        String vin = row.get("vin").toString();
        String productGroupName = row.get("productGroupName").toString();
        String znbbm = row.get("znbbm").toString();

        System.out.println("vin: " + vin);
        System.out.println("产品组: " + productGroupName);
        System.out.println("内部编号: " + znbbm);

    }

    public static String getNowTime() {
        return LocalTime.now().toString();
    }
}